package com.app.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * User: lb on 2017/2/13.
 * Date:2017-02-13-15:15
 * desc：
 */
@RestController
public class EsController {

//    @Autowired
//    private Client myClient;

    @RequestMapping("/getIndex")
    public String getIndex() {
        String strTmp2 = "12";
        try {
            byte[] addr = new byte[]{127, 0, 0, 1};
            TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByAddress(addr), 9300));
//			IndexResponse response = client.prepareIndex("world", "hello", "1")
//					.setSource(jsonBuilder()
//							.startObject()
//							.field("user", "kimchy")
//							.field("postDate", new Date())
//							.field("message", "trying out Elasticsearch")
//							.endObject()
//					)
//					.get();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("user", "mytest5");
            //      jsonObject.put("postDate",new Date());日期直接使用有格式的问题。
            jsonObject.put("message", "mymessage5");
            JSONArray jsonArray = new JSONArray();
            jsonArray.add("test41");
            jsonArray.add("test42");
            jsonObject.put("testarray", jsonArray);
            String message = jsonObject.toString();
            IndexResponse response = client.prepareIndex("china", "anhui", "1").setSource(message).get();
            GetResponse response2 = client.prepareGet("china", "anhui", "1").get();
            strTmp2= client.prepareGet().setIndex("china").toString();
            System.out.println("strTmp2=" + strTmp2);
            client.close();
        } catch (Exception e) {
            //
        }
        return strTmp2;
    }
}
